#include "localinterface.h"

LocalInterface::LocalInterface(XMLInterface *x, QObject *parent) :
    QObject(parent)
{
    xml = x;

    artourDir = new QDir(QDir::homePath());

    if (artourDir->exists(ARTOUR_LOCAL_DIR))
    {
        artourDir->cd(ARTOUR_LOCAL_DIR);
    }
    else
    {
        artourDir->mkdir(ARTOUR_LOCAL_DIR);
        artourDir->cd(ARTOUR_LOCAL_DIR);
    }
}

void LocalInterface::readLocalXml()
{
    xml->readXML(artourDir->absoluteFilePath("artour.xml"));
    updatePaths();
}

/**
  Updates the paths of all props. If the prop data is not in the directory, create symlinks.
  TODO: After this is called, should remove unused info from the dir, then copy dir to device.
  */
void LocalInterface::updatePaths()
{
    /*if (!xml->buildXML(artourDir->absoluteFilePath("artour.xml"), true))
    {
        // buildXML() failed for some reason, probably because minimap data is missing
        emit logMessage("Save to device cancelled (if you didn't cause this, yell at the programmer)", IMPORTANT);
        return;
    }*/
    std::vector<PropData *> props = xml->getAllProps();

    // copy xml, delete old if necessary
    /*if (artourDir->exists("artour.xml"))
    {
        artourDir->remove("artour.xml");
    }
    QFile::copy(xml->getTmpXmlFile(), artourDir->absoluteFilePath("artour.xml"));*/

    // minimap
    PropData *map = xml->getMinimap();
    if (map != NULL && map->pic.size() > 0)
    {
        if (!artourDir->exists("Minimap"))
        {
            artourDir->mkdir("Minimap");
        }
        artourDir->cd("Minimap");
        if (map->pic[0]->first == "")
        {
            // file is from the device
            // The file should already exist here w/ the same file name, just get that file name
            // TODO: possibly verify existence
            qDebug() << "fn: " + getFileName(map->pic[0]->second);
            map->pic[0]->first = artourDir->absoluteFilePath(getFileName(map->pic[0]->second));
        }
        else
        {
            QFileInfo mfile(map->pic[0]->first);
            //map->pic[0]->first = linkFile(map->pic[0]->first);
            QString mappath = artourDir->absoluteFilePath(mfile.fileName());
            qDebug() << map->pic[0]->first;
            qDebug() << mappath;
            QFile::copy(map->pic[0]->first, mappath);
            map->pic[0]->first = mappath;
        }
        artourDir->cdUp();
    }

    for (unsigned int k = 0; k < props.size(); k++)
    {
        // check if a folder exists for the prop
        if (!artourDir->exists(props[k]->getPropName()))
        {
            artourDir->mkdir(props[k]->getPropName());
        }
        artourDir->cd(props[k]->getPropName());

        for (unsigned int j = 0; j < props[k]->aud.size(); j++)
        {
            if (props[k]->aud[j]->first == "")
            {
                // file is from the device
                // The file should already exist here w/ the same file name, just get that file name
                // TODO: possibly verify existence
                props[k]->aud[j]->first = artourDir->absoluteFilePath(getFileName(props[k]->aud[j]->second));
            }
            else
            {
                // file is on the local machine
                props[k]->aud[j]->first = linkFile(props[k]->aud[j]->first);
            }
        }
        for (unsigned int j = 0; j < props[k]->vid.size(); j++)
        {
            if (props[k]->vid[j]->first == "")
            {
                // file is from the device
                // The file should already exist here w/ the same file name, just get that file name
                // TODO: possibly verify existence
                props[k]->vid[j]->first = artourDir->absoluteFilePath(getFileName(props[k]->vid[j]->second));
            }
            else
            {
                props[k]->vid[j]->first = linkFile(props[k]->vid[j]->first);
            }
        }
        for (unsigned int j = 0; j < props[k]->pic.size(); j++)
        {
            if (props[k]->pic[j]->first == "")
            {
                // file is from the device
                // The file should already exist here w/ the same file name, just get that file name
                // TODO: possibly verify existence
                props[k]->pic[j]->first = artourDir->absoluteFilePath(getFileName(props[k]->pic[j]->second));
            }
            else
            {
                props[k]->pic[j]->first = linkFile(props[k]->pic[j]->first);
            }
        }
        artourDir->cdUp();
    }

    xml->buildXML(artourDir->absoluteFilePath("artour.xml"), true);
}

// assumes artourDir is currently set to a prop directory
QString LocalInterface::linkFile(QString src)
{
    QString fpath(src);
    QFileInfo f(fpath);
    QFileInfo flnk(fpath + ".lnk");
    fpath.replace('\\', '/');
    QFileInfo fdir(artourDir->absoluteFilePath(getFileName(fpath)));
    QFileInfo flnkdir(artourDir->absoluteFilePath(getFileName(fpath) + ".lnk"));
    if (!fdir.exists() && !flnkdir.exists())
    {
        // file is not in the prop directory
        // create a link
        QString linkpath = artourDir->absoluteFilePath(f.fileName());
        if (flnk.exists())
            QFile::link(flnk.symLinkTarget(), linkpath + ".lnk");
        else
            QFile::link(f.absoluteFilePath(), linkpath + ".lnk");
        linkpath.replace(".lnk", "");
        return linkpath;
    }
    return src;
}

QString LocalInterface::getFileName(QString path)
{
    int index = path.lastIndexOf('/');
    if (index == -1)
    {
        return path;
    }
    else
    {
        return path.mid(index + 1);
    }
}

void LocalInterface::removePropFolder(QString folderName)
{
    QString path = artourDir->absoluteFilePath(folderName);
    qDebug() << path;
    // QDir::rmdir() requires an empty directory and I am lazy
#ifdef Q_WS_WIN
    system(QString("rd /S /Q \"" + path + "\"").toAscii());
#endif
#ifdef Q_WS_X11
    system(QString("rm -rf " + path).toAscii());
#endif
}

void LocalInterface::removeAll()
{
    QFileInfoList fi = artourDir->entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
    for (int k = 0; k < fi.size(); k++)
    {
        if (fi[k].isDir())
        {
            removePropFolder(fi[k].fileName());
        }
        else
        {
            artourDir->remove(fi[k].fileName());
        }
    }
}

QString LocalInterface::copyToDir(QString srcFile, QDir *destFolder)
{
    bool success = true;
    QFileInfo f(srcFile);
    if (!f.exists() || !destFolder->exists())
    {
        return "";
    }
    success = QFile::copy(srcFile, destFolder->absoluteFilePath(f.fileName()));
    if (success)
        return destFolder->absoluteFilePath(f.fileName());
    else
        return "";
}

void LocalInterface::writeDataToDir()
{
    QString newpath = "";
    if (!xml->buildXML())
    {
        // buildXML() failed for some reason, probably because minimap data is missing
        emit logMessage("Save to device cancelled (if you didn't cause this, yell at the programmer)", IMPORTANT);
        return;
    }
    std::vector<PropData *> props = xml->getAllProps();

    // copy xml, delete old if necessary
    if (artourDir->exists("artour.xml"))
    {
        artourDir->remove("artour.xml");
    }
    QFile::copy(xml->getTmpXmlFile(), artourDir->absoluteFilePath("artour.xml"));

    // minimap
    if (xml->getMinimap() != NULL && xml->getMinimap()->pic.size() > 0)
    {
        artourDir->mkdir("Minimap");
        artourDir->cd("Minimap");
        newpath = copyToDir(xml->getMinimap()->pic[0]->first, artourDir);
        if (newpath != "")
        {
            xml->getMinimap()->pic[0]->first = newpath;
        }
        artourDir->cdUp();
    }

    // props
    for (unsigned int k = 0; k < props.size(); k++)
    {
        artourDir->mkdir(props[k]->getPropName());
        artourDir->cd(props[k]->getPropName());

        for (unsigned int j = 0; j < props[k]->aud.size(); j++)
        {
            newpath = copyToDir(props[k]->aud[j]->first, artourDir);
            if (newpath != "")
            {
                props[k]->aud[j]->first = newpath;
            }
        }
        for (unsigned int j = 0; j < props[k]->vid.size(); j++)
        {
            newpath = copyToDir(props[k]->vid[j]->first, artourDir);
            if (newpath != "")
            {
                props[k]->vid[j]->first = newpath;
            }
        }
        for (unsigned int j = 0; j < props[k]->pic.size(); j++)
        {
            newpath = copyToDir(props[k]->pic[j]->first, artourDir);
            if (newpath != "")
            {
                props[k]->pic[j]->first = newpath;
            }
        }

        artourDir->cdUp();
    }
}
